<?php
class Zendvn_Model_Table_Product extends Zend_Db_Table{
	protected $_tableClass = 'Zendvn_Model_Table_Product';
	protected $_name = "products";
	protected $_primary = "id"; 
	protected $_arrParam = array();
	
	public $_searchFields 	= array(
									'name'				=>'- Name',
									'id'				=>'- ID',
									'content'			=>'- Content',
									'html_descript'		=>'- Html description',
									'html_keyword'		=>'- Html keyword',
									'created'			=>'- Created',
									'created_by'		=>'- Created by',
									'modified'			=>'- Modified',
									'modified_by'		=>'- Modified by',
									);
	
	protected $_listSQL;
	
	public function statusItem($arrParam = null,$options = null){
		if($options == null){
			$status = 'active';
			if($arrParam['s'] == 'active') $status = 'inactive';
			if($arrParam['s'] == 'inactive') $status = 'lock';
			$data = array('status'=>$status);
			$where = 'id = ' . (int)$arrParam['id'];
			$this->update($data, $where);	
		}
		
		if($options['task'] == 'multi'){
			
			$status = $arrParam['s'];				
			if(count($arrParam['cid'])>0){
				if($status == 'active'){
					$ids = implode(',', $arrParam['cid']);
					$where = 'id IN (' . $ids . ')';
					$data = array('status'=>$status);
					$this->update($data, $where);
				}else{
					foreach ($arrParam['cid'] as $val){						
						$where = 'id = ' . $val;
						$data = array('status'=>$status);
						$this->update($data, $where);						
					}
				}
			}
		}
	}
	
	public function deleteItem($arrParam = null,$options = null){
		if($options == null){
			if((int)$arrParam['id']>0){
				$config = new Zendvn_Controller_Config(array('module'=> $arrParam['module'],
													 	  'fileConfig'=>'product-category.ini'));
				$imageConfig = $config->getConfig('item');
				
				$itemInfo = $this->getItem(array('id'=>$arrParam['id']));
				
				$file = new Zendvn_File_Upload();
				$avatarConfig = $config->getConfig('item');
				$file->remove($imageConfig['uploadDir'],$itemInfo['image']);				
				$file->remove($imageConfig['thumbDir1'],$itemInfo['image']);	
				$file->remove($imageConfig['thumbDir2'],$itemInfo['image']);	

				if(!empty($itemInfo['images'])){
					$arrImg = json_decode($itemInfo['images'], true);
					foreach ($arrImg as $k => $v){
						$file->remove($imageConfig['uploadDir'],$v);				
						$file->remove($imageConfig['thumbDir1'],$v);	
						$file->remove($imageConfig['thumbDir2'],$v);
					}
				}
				
				$where = 'id = ' . (int)$arrParam['id'];
				$this->delete($where);
			}
		}
		if($options['task'] == 'multi'){		
			if(count($arrParam['cid'])>0){	
				$config = new Zendvn_Controller_Config(array('module'=> $arrParam['module'],
													 	  'fileConfig'=>'product-category.ini'));
				$imageConfig = $config->getConfig('item');					
						
				$file = new Zendvn_File_Upload();
				foreach ($arrParam['cid'] as $val){
					$itemInfo = $this->getItem(array('id'=> $val));
					
					$file = new Zendvn_File_Upload();
					$avatarConfig = $config->getConfig('item');
					$file->remove($imageConfig['uploadDir'],$itemInfo['image']);				
					$file->remove($imageConfig['thumbDir1'],$itemInfo['image']);	
					$file->remove($imageConfig['thumbDir2'],$itemInfo['image']);	
	
					if(!empty($itemInfo['images'])){
						$arrImg = json_decode($itemInfo['images'], true);
						foreach ($arrImg as $k => $v){
							$file->remove($imageConfig['uploadDir'],$v);				
							$file->remove($imageConfig['thumbDir1'],$v);	
							$file->remove($imageConfig['thumbDir2'],$v);
						}
					}
					$where = 'id = ' . (int)$val;
					$this->delete($where);
				}
			}
		}
	}
	public function getItem($arrParam = null,$options = null){
		
		if($options == null){
			$where = 'id = ' . (int)$arrParam['id'];
			$result = $this->fetchRow($where)->toArray();
		}
		if($options['task'] == 'custome'){
			$db = $this->getAdapter();
			$select = $db->select()
						->from($this->_name . ' AS i',$options['fields'])
						->where('i.id = ?', (int)$arrParam['id'],'INTERGE');
			$result = $db->fetchRow($select);
		}		
		/* if($options['task'] == 'list-child'){
			$item = $this->getCat($arrParam, array('task' => 'get-child'));
			if(count($item) >0 ){
				foreach($item as $key => $val){
					$ids[] = $key;
				}
			}else {
				$ids[] = $arrParam['id'];
			}
			$db = $this->getAdapter();
			$select = $db->select()
						 ->from($this->_name . ' AS i')
						 ->joinLeft('product_categories AS c', 'i.cat_id = c.id', array ('c.name AS cat_name' ))
						 ->where('i.cat_id IN (?)', $ids)
						 ->where('i.status = ?', 'active');
						 
			$this->_listSQL = $select;
						 
			$panigator = $arrParam['panigator'];	
			$select->limitPage($panigator['page'], $panigator['rowCount']);
			$result = $db->fetchAll($select);
			return $result;
		}	 */
		
		if($options['task'] == 'info'){
			
			$db = $this->getAdapter();
			$select = $db->select()
						->from($this->_name . ' AS i')						
						->where('i.id = ?',$arrParam['id'],1)
						->joinLeft('product_categories AS c', 'c.id = i.cat_id', array ('c.name AS cat_id' ))
						->joinLeft('users AS u1','u1.id = i.created_by', array ('u1.email AS created_by'))
						->joinLeft('users AS u2','u2.id = i.modified_by',array ('u2.email AS modified_by'));			
			$result = $db->fetchRow($select);		
		}	
		return $result;
	}
	
	public function listItem($arrParam = null,$options = null){
		
		if($options == null){
			$db = $this->getAdapter();
			$select = $db->select()
						 ->from($this->_name . ' AS i')
						 ->joinLeft('product_categories AS c', 'i.cat_id = c.id', array ('c.name AS cname' ))
						 ->joinLeft('users AS u1','u1.id = i.created_by', array ('u1.email AS cemail'))
						 ->joinLeft('users AS u2','u2.id = i.modified_by',array ('u2.email AS memail'));
			$arrFilter = $arrParam['arrFilter'];
			
			if(!empty($arrFilter['col'])){
				$select->order($arrFilter['col'] . ' ' . $arrFilter['order']);			
			}
	
			if(!empty($arrFilter['status']) && $arrFilter['status'] != 'none'){
				$select->where('i.status = ?',$arrFilter['status']);
			}
			
			if(!empty($arrFilter['cat_id']) && $arrFilter['cat_id'] != 1){
				$tblProductCategories 		= new Zendvn_Model_Table_ProductCategories();
				$arrCid 					= $tblProductCategories->getChildrenNode($arrFilter['cat_id'],array('node'=>true,'fields'=>array('id')));
				$select->where('i.cat_id IN (?)',$arrCid);
			}
			
			if(!empty($arrFilter['keyword']) && !empty($arrFilter['searchField'])){
				$keyword = '%' . $arrFilter['keyword'] . '%';
				$select->where('i.'.$arrFilter['searchField'] . ' LIKE ? ', $keyword);
			}
			
			$this->_listSQL = $select;
			$panigator = $arrParam['panigator'];	
			$select->limitPage($panigator['page'], $panigator['rowCount']);
			
			$result = $db->fetchAll($select);		 
		}else {
			$this->_arrParam = $arrParam;
			$functionName = $this->call($options['task']);
			$result = $this->$functionName();
		}
		return $result;
	}
	public function totalItem($arrParam = null,$options = null){
		
		if($options == null){
			$db = $this->getAdapter();
			$select = $this->_listSQL->reset(Zend_Db_Select::COLUMNS);
			$select = $this->_listSQL->reset(Zend_Db_Select::LIMIT_COUNT);
			$select = $this->_listSQL->reset(Zend_Db_Select::LIMIT_OFFSET);
			$select = $this->_listSQL->reset(Zend_Db_Select::ORDER);
			$select = $this->_listSQL->reset(Zend_Db_Select::GROUP);
			$select->columns('COUNT(i.id) AS total');	
			$result = $db->fetchOne($select);
		}
		if($options['task'] == 'public'){
			$db = $this->getAdapter();
			$select = $this->_listSQL->reset(Zend_Db_Select::COLUMNS);
			$select = $this->_listSQL->reset(Zend_Db_Select::LIMIT_COUNT);
			$select = $this->_listSQL->reset(Zend_Db_Select::LIMIT_OFFSET);
			$select = $this->_listSQL->reset(Zend_Db_Select::ORDER);
			$select = $this->_listSQL->reset(Zend_Db_Select::GROUP);
			$select->columns('COUNT(i.id) AS total');	
			//echo '<br>' . $select;
			$result = $db->fetchOne($select);
		}
		return $result;
		
	}
	
	public function saveItem($arrParam = null,$options = null){
		
		$function  = Zendvn_System_Function::call($options['task']);
		$this->$function($arrParam);
	}
	public function adminAdd($arrParam = null){
		$info 				= new Zendvn_System_Info();
		$idUser 			= $info->getMemberInfo('id');
		
		$row 				= $this->fetchNew();
		
		$row->name			= $arrParam['name'];			
		$row->image			= $arrParam['image'];
		$row->images		= json_encode($arrParam['images_hidden']);
		$row->content		= $arrParam['content'];
		$row->html_descript	= $arrParam['html_descript'];	
		$row->html_keyword	= $arrParam['html_keyword'];						
		$row->views			= $arrParam['views'];						
		$row->tags			= $arrParam['tags'];						
		$row->status		= ($arrParam['status']=='') ? 'inactive':$arrParam['status'];
		$row->created		= date('Y-m-d H:i:s');
		$row->created_by	= $idUser;
		$row->params		= Zend_Json::encode($arrParam['cparam']);
		$row->cat_id		= $arrParam['cat_id'];	
		$row->special		= $arrParam['special'];	
		$row->save();
			
	}
	
	public function adminEdit($arrParam = null){
	
		$info 				= new Zendvn_System_Info();
		$idUser 			= $info->getMemberInfo('id');
		
		$where  			= 'id = ' . (int)$arrParam['id'];
		$row 				= $this->fetchRow($where);
		$row->name			= $arrParam['name'];	
		$row->image			= ($arrParam['image']) ? $arrParam['image'] : $arrParam['current_image'];	
		$row->images		= json_encode($arrParam['images_hidden']);	
		$row->content		= $arrParam['content'];
		$row->html_descript	= $arrParam['html_descript'];	
		$row->html_keyword	= $arrParam['html_keyword'];						
		$row->views			= $arrParam['views'];						
		$row->tags			= $arrParam['tags'];						
		$row->status		= ($arrParam['status']=='') ? 'inactive':$arrParam['status'];
		$row->modified		= date('Y-m-d H:i:s');
		$row->modified_by	= $idUser;
		$row->params		= Zend_Json::encode($arrParam['cparam']);
		$row->cat_id		= $arrParam['cat_id'];
		$row->special		= $arrParam['special'];
		$row->save();
	}
	public function uploadImages($arrParam = null,$options = null){
	
		$where  	= 'id = ' . (int)$arrParam['id'];
		$row 		= $this->fetchRow($where);
	
		if($row->image != null){
			$arrImg = Zend_Json::decode($row->image);
			$arrImg[] = $arrParam['images'];
		}else {
			$arrImg = array($arrParam['images']);
		}
	
		$arrImg = Zend_Json::encode($arrImg);
	
		$row->image = $arrImg;
		$row->save();
	
	}
	public function removeImages($arrParam = null,$options = null){
	
		$where  	= 'id = ' . (int)$arrParam['id'];
		$row 		= $this->fetchRow($where);
		
		if($row->image != '' && $arrParam['file'] != ''){
			$arrImg = Zend_Json::decode($row->images);
			$arrImg = array_diff($arrImg,array($arrParam['file']));
			$arrImg = Zend_Json::encode($arrImg);
			$row->images = $arrImg;
			$row->save();
		}
	}
}